package tasks.leetcode.算法通关;

public class MaxProfit {

    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit2(prices));
    }

    /**
     * 问题:会超出时间限制
     *
     * @param prices
     * @return
     */
    private static int maxProfit(int[] prices) {
        if (prices.length <= 1) {
            return 0;
        }
        int maxtProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = 0; j < i; j++) {
                if (prices[i] - prices[j] > maxtProfit) {
                    maxtProfit = prices[i] - prices[j];
                }
            }
        }
        return maxtProfit;
    }

    private static int maxProfit2(int[] prices) {

        int minPrice = Integer.MAX_VALUE;

        if (prices.length <= 1) {
            return 0;
        }
        int maxtProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else if (prices[i] - minPrice > maxtProfit) {
                maxtProfit = prices[i] - minPrice;
            }
        }
        return maxtProfit;
    }
}
